package com.tyqx.hashchainbiz.controller.jzt;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tyqx.hashchainbean.module.*;
import com.tyqx.hashchainbean.vo.JZTGS1StrVO;
import com.tyqx.hashchainbean.vo.JZTGS1VO;
import com.tyqx.hashchainbean.vo.MongoDbInfoVO;
import com.tyqx.hashchainbiz.controller.config.JwtTokenUtil;
import com.tyqx.hashchainbiz.service.*;
import com.tyqx.hashchainutil.common.mongodb.ImagePathHashValueUtil;
import hashchainutil.common.Dto;
import hashchainutil.common.DtoUtil;
import hashchainutil.common.EmptyUtils;
import org.apache.commons.lang.StringUtils;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/JZTApi/GS1")
@CrossOrigin
public class JZTGS1Controller {

    @Resource
    private JZTGS1Service jztgs1Service;

    @Resource
    private TrackUserService trackUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private MysqlDataBaseAndMongDbConfigService mysqlDataBaseAndMongDbConfigService;

    @RequestMapping(value = "/addJZTGS1", method = RequestMethod.POST)
    @ResponseBody
    public Dto addJZTGS1(@RequestBody JZTGS1 jztgs1, HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String tokenUserName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        String userName = jztgs1.getUserName();
        TrackUser trackUser = trackUserService.getUserByCode(userName);
        if (EmptyUtils.isEmpty(trackUser)) {
            String msg = "用户找不到";
            return DtoUtil.returnFail(msg, "100006");
        }

        if (!tokenUserName.equals(userName)) {
            String msg = "用户名跟token用户名不匹配";
            return DtoUtil.returnFail(msg, "100005");
        }
        String msg = "";


        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;
        List<JZTGS1> jztgs1List=new ArrayList<>();
        boolean flag=false;
        jztgs1List.add(jztgs1);

        MongoDbInfoVO mongoDbInfoVO = new MongoDbInfoVO();
        if (jztgs1List.size() > 0) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            String jztLogisticsListStr = gson.toJson(jztgs1List);
            CryptoPrimitives suite = new CryptoPrimitives();
            suite.init();
            String hashValue1 = ImagePathHashValueUtil.getHashValue(jztLogisticsListStr, suite);

            mongoDbInfoVO.setHashValue(hashValue1);
            mongoDbInfoVO.setInfoList(jztgs1List);
            mongoDbInfoVO.setInfoTableName("jzt_GS1");

            String collName = "jztGS1List";


            double dataCount = jztgs1List.size();
            String dataType = "jztGS1List";
            HashChainStatistics hashChainStatistics = new HashChainStatistics();
            hashChainStatistics.setDataCount(dataCount);
            hashChainStatistics.setDataType(dataType);
            hashChainStatistics.setUserName(jztgs1List.get(0).getUserName());
            hashChainStatistics.setCreateTime(createTime);
            hashChainStatistics.setUpdateTime(updateTime);
            flag=mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDB(hashChainStatistics, collName, mongoDbInfoVO);
        }
        if (flag) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else {
            msg = "信息上链失败";
            return DtoUtil.returnFail(msg, "100001");
        }
    }

    @RequestMapping(value = "/batchAddJZTGS1", method = RequestMethod.POST)
    @ResponseBody
    public Dto batchAddJZTGS1(@RequestBody List<JZTGS1> jztgs1List, HttpServletRequest request) throws Exception {
        // verify token username against data username
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        TrackUser trackUser = trackUserService.getUserByCode(userName);
        List<JZTGS1> jztGS1ListError = new ArrayList<>();
        int size = jztgs1List.size();
        for (int i = 0; i < size; i++) {
            JZTGS1 jztgs1 = jztgs1List.get(i);
            if (EmptyUtils.isEmpty(trackUser) || !userName.equals(jztgs1.getUserName())) {
                jztGS1ListError.add(jztgs1);
            }
        }
        if (jztGS1ListError.size() > 0) {
            for (int j = 0; j < jztGS1ListError.size(); j++) {
                jztgs1List.remove(jztGS1ListError.get(j));
            }
        }
        List<JZTGS1Str> jztgs1StrList=new ArrayList<>();

        String msg = "";

        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;

        MongoDbInfoVO mongoDbInfoVO = new MongoDbInfoVO();
        if (jztgs1List.size() > 0) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            String jztLogisticsListStr = gson.toJson(jztgs1List);
            CryptoPrimitives suite = new CryptoPrimitives();
            suite.init();
            String hashValue = ImagePathHashValueUtil.getHashValue(jztLogisticsListStr, suite);

            mongoDbInfoVO.setHashValue(hashValue);
            mongoDbInfoVO.setInfoList(jztgs1List);
            mongoDbInfoVO.setInfoTableName("jzt_GS1");

            String collName = "jztGS1List";


            double dataCount = jztgs1List.size();
            String dataType = "jztGS1List";
            HashChainStatistics hashChainStatistics = new HashChainStatistics();
            hashChainStatistics.setDataCount(dataCount);
            hashChainStatistics.setDataType(dataType);
            hashChainStatistics.setUserName(jztgs1List.get(0).getUserName());
            hashChainStatistics.setCreateTime(createTime);
            hashChainStatistics.setUpdateTime(updateTime);
            /*Integer flag=hashChainStatisticsService.add(hashChainStatistics);
            flag=0;
            if (flag == 0){
                throw new Exception("record statistcs error");
            }
            mongoDBUtil.insertOne(collName,mongoDbInfoVO);*/
            mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDB(hashChainStatistics, collName, mongoDbInfoVO);
        }

        if (jztGS1ListError.size() == 0 && EmptyUtils.isNotEmpty(mongoDbInfoVO.getId())) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else if (jztgs1List.size() == 0 && jztGS1ListError.size() > 0) {
            msg = "信息上链失败,信息包含的用户名不正确";
            return DtoUtil.returnFail(msg, "100001");
        } else {
            msg = "success: " + jztgs1List.size() + ", fail: " + jztGS1ListError.size() + ",用户名不正确信息上链失败";
            return DtoUtil.returnSuccess(msg, "100002");
        }
    }

    @RequestMapping(value = "/getJZTGS1BySsccCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTGS1BySsccCode(@RequestParam(value = "ssccCode", required = true) String ssccCode,HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        List<JZTGS1StrVO> jztgs1StrVOList = jztgs1Service.grantGetJZTGS1BySsccCode(ssccCode,userName);
        List<JZTGS1VO> jztgs1VOList=new ArrayList<>();
        for (int i=0;i<jztgs1StrVOList.size();i++){
            JZTGS1StrVO jztgs1StrVO=jztgs1StrVOList.get(i);
            String userName1 = jztgs1StrVO.getUserName();
            Date arrivalTime = jztgs1StrVO.getArrivalTime();
            String billType=jztgs1StrVO.getBillType();
            String billTypeName=jztgs1StrVO.getBillTypeName();
            Date createTime=jztgs1StrVO.getCreateTime();
            String departureAddress=jztgs1StrVO.getDepartureAddress();
            String fromCorpName=jztgs1StrVO.getFromCorpName();
            String hashValue=jztgs1StrVO.getHashValue();
            String operator=jztgs1StrVO.getOperator();
            Date operatorTime=jztgs1StrVO.getOperatorTime();
            String ssccCode1=jztgs1StrVO.getSsccCode();
            String toCorpName=jztgs1StrVO.getToCorpName();
            Date storeOutDate=jztgs1StrVO.getStoreOutDate();
            String subSsccCode=jztgs1StrVO.getSubSsccCode();
            String tprtMode=jztgs1StrVO.getTprtMode();
            String transportMode=jztgs1StrVO.getTransportMode();
            String transportSsa=jztgs1StrVO.getTransportSsa();
            Date transportTime=jztgs1StrVO.getTransportTime();
            Date updateTime=jztgs1StrVO.getUpdateTime();

            String[] subSsccCodeArray= subSsccCode.split(",");

            JZTGS1VO jztgs1VO=new JZTGS1VO();
            jztgs1VO.setUserName(userName1);
            jztgs1VO.setArrivalTime(arrivalTime);
            jztgs1VO.setBillType(billType);
            jztgs1VO.setBillTypeName(billTypeName);
            jztgs1VO.setCreateTime(createTime);
            jztgs1VO.setDepartureAddress(departureAddress);
            jztgs1VO.setFromCorpName(fromCorpName);
            jztgs1VO.setHashValue(hashValue);
            jztgs1VO.setOperator(operator);
            jztgs1VO.setOperatorTime(operatorTime);
            jztgs1VO.setSsccCode(ssccCode);
            jztgs1VO.setStoreOutDate(storeOutDate);
            jztgs1VO.setSubSsccCode(subSsccCodeArray);
            jztgs1VO.setToCorpName(toCorpName);
            jztgs1VO.setTprtMode(tprtMode);
            jztgs1VO.setTransportMode(transportMode);
            jztgs1VO.setTransportSsa(transportSsa);
            jztgs1VO.setTransportTime(transportTime);
            jztgs1VO.setUpdateTime(updateTime);

            jztgs1VOList.add(jztgs1VO);
        }
        if (jztgs1VOList.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztgs1VOList);
        } else {
            return DtoUtil.returnSuccess("未查询到记录", "");
        }
    }
}
